/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
#include "memory.h"

static PLIST _delete(PLIST sp_head, PLIST sp_delete) {
	if (sp_delete == sp_head) {
		sp_head = sp_head->next;
	} else {
		PLIST sp_find = sp_head;
		while (sp_find->next != sp_delete) {
			sp_find = sp_find->next;
		}
		if (sp_delete->next == NULL) {
			sp_find->next = NULL;
		} else {
			sp_find->next = sp_delete->next;
		}
	}
	//printf("free index : [%d] => value : %s \n", sp_delete->index, sp_delete->value);
	tj_memory_free(sp_delete);
	return sp_head;
}

static PLIST _create_element(void* value) {
	PLIST sp_link = (PLIST) tj_memory_alloc(sizeof(LIST));
	if (!sp_link) {
		printf("memory allocate fail! \n");
		exit(1);
	}
	sp_link->value = value;
	sp_link->next = NULL;
	return sp_link;
}

PLIST tj_list_add(PLIST sp_head, void* value) {
	PLIST sp_new = _create_element(value);
	if (NULL == sp_head) {
		return sp_new;
	}
	PLIST sp_last = sp_head;
	while (sp_last->next != NULL) {
		sp_last = sp_last->next;
	}
	sp_last->next = sp_new;
	return sp_head;
}

PLIST tj_ists_find(PLIST sp_head, void* value) {
	PLIST result = sp_head;
	while (result != NULL) {
		if (result->value == value) {
			return result;
		}
		result = result->next;
	}
	return NULL;
}

PLIST tj_list_delete(PLIST sp_head, void* value) {
	PLIST sp_delete = tj_ists_find(sp_head, value);
	if (NULL != sp_delete) {
		return _delete(sp_head, sp_delete);
	}
	return sp_head;
}

PLIST tj_list_destroy(PLIST sp_head) {
	PLIST sp_current;
	while (sp_head != NULL) {
		sp_current = sp_head;
		sp_head = sp_head->next;
		//printf("free index PLISTS [%p] : [%d] [%p] \n", sp_current, sp_current->index, sp_current->value);
		tj_memory_free(sp_current);
		sp_current = NULL;
	}
	return sp_head;
}
